package cn.tedu.eb_film.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 上传工具类
 *
 * @author ライナー・ロンテ
 * @since 2023/3/17 20:03
 */
@Slf4j
@Component
public class OssUtils {

    public static String upload(MultipartFile file, String endpoint
            , String accessKeyId
            , String accessKeySecret
            , String bucketName) {

        log.debug("开始文件上传服务,文件名字为{}", file.getName());
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(new Date());

        if (file == null) {
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            filename = bucketName + "/" + dateStr + "/" + uuid + suffix;
            PutObjectResult result = ossClient.putObject(bucketName, filename, file.getInputStream());
            /*设置公开读*/
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                log.debug("文件上传成功");
            }

            return "https://" + bucketName +"."+ endpoint + "/" + filename;
        } catch (OSSException e) {
            log.error(e.getMessage());
        } catch (ClientException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
